const query = require('../../db/index');

// 根据 articleId 搜索文章，根据 content 模糊匹配文章的 title 和 content 字段
exports.getArticle = async (req, res) => {
    try {
        const { articleId, content } = req.query;
        let searchSQL = `
            SELECT a.*, IFNULL(GROUP_CONCAT(t.name), '') AS tagNames
            FROM article a
            LEFT JOIN settags st ON a.articleId = st.articleId
            LEFT JOIN tags t ON st.tagsId = t.tagsId
        `;
        const searchValues = [];

        // 根据参数动态构建查询条件
        if (articleId) {
            searchSQL += `
                WHERE a.articleId = ?
            `;
            searchValues.push(articleId);
        } else if (content) {
            searchSQL += `
                WHERE a.title LIKE ? OR a.content LIKE ?
            `;
            const searchTerm = `%${content}%`;
            searchValues.push(searchTerm, searchTerm);
        }

        searchSQL += `
            GROUP BY a.articleId
        `;

        const searchResult = await query(searchSQL, searchValues);
        if (searchResult.length === 0) {
            return res.dispatch(404, "No matching articles found");
        }
        // 将 tagNames 字段处理为数组
        searchResult.forEach(article => {
            article.tagNames = article.tagNames ? article.tagNames.split(',') : [];
        });
        return res.dispatch(200, "Success", searchResult);
    } catch (error) {
        return res.dispatch(500, "Internal Server Error");
    }
}